package LDAP;

import java.util.HashMap;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

/**
 * ParamÃ¨tres de config LDAP
 * @author Denis Jouvin
 */
public class Ldap {
    // PrÃ©paration de la connexion au serveur LDAP
    private final Hashtable env = new Hashtable();
    private final String searchBase = "dc=univ-lyon1,dc=fr";
    private final SearchControls searchControls = new SearchControls();

    public Ldap() {
		// Note: il est possible de spÃ©cifier l'environnement dans un fichier ldap.properties
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, "ldap://projet-m1-if.univ-lyon1.fr:389");
		searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
		searchControls.setCountLimit(1);
		searchControls.setTimeLimit(5000);
	}

	/**
	 * @return true if the user was found
	 */
	public HashMap<String, String> search(String subtree, String filter) throws NamingException {
            HashMap<String, String> result = new HashMap<String, String>();
		try {
			InitialDirContext ctx = new InitialDirContext(env);
                        String base = subtree+','+searchBase;
			NamingEnumeration<SearchResult> results = ctx.search(base, filter, searchControls);
			if(results.hasMore()) {
				SearchResult entry = results.next();
				Attributes attr = entry.getAttributes();
                                NamingEnumeration ids = attr.getIDs();
                                while(ids.hasMore()) {
                                    String id = (String) ids.next();
                                    result.put(id, attr.get(id).get().toString());
                                }
                                return result;
			}
		}
		catch (NamingException e) {
			throw new NamingException();
		}
                return null;
	}
}
